package kr.co.mustgo.controller.review;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.mustgo.domain.review.Comment;
import kr.co.mustgo.domain.review.ReviewsBoard;
import kr.co.mustgo.model.service.review.ReviewsService;
import kr.co.mustgo.util.FileUpload;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/reviewsboard/")
public class ReviewsController {

	@Autowired
	private ReviewsService reviewsService;

	@RequestMapping("uploader.do")
	public String fileUpload(Model model, MultipartRequest multipartRequest, HttpServletRequest request) throws IOException{
		MultipartFile imgfile = multipartRequest.getFile("Filedata");	//글쓰기 부분에서 input file의 name
		Calendar cal = Calendar.getInstance();
		String fileName = imgfile.getOriginalFilename();
		String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
		String replaceName = cal.getTimeInMillis() + fileType;
		String path = request.getSession().getServletContext().getRealPath("/")+"upload";//파일 저장 경로
		
		FileUpload.fileUpload(imgfile, path, replaceName);
		model.addAttribute("path", path);	//파일업로드를 하는 창에 경로와
		model.addAttribute("filename", replaceName);	//저장된 이름을 전달
		return "/file_upload.jsp";
	}
	
	// 새글 입력 폼으로 이동 처리하는 handler 메소드
	@RequestMapping("write_form.do")
	public String writeForm() {
		return "tiles/reviewsboard/write_form.jsp";
	}

	// 새글을 등록처리하는 handler 메소드
	@RequestMapping("writePost.do")
	public ModelAndView writePost(ReviewsBoard board) {
		ModelAndView mv = null;
		String saveDir = "C:\\day\\apache-tomcat-6.0.41\\webapps\\must_go\\upload_picture";
		List<MultipartFile> upfile = board.getUpfile();
		String fileName = "";
		try {
			if (upfile != null) {
				for (MultipartFile file : upfile) {
					if (!file.isEmpty()) {
						String fileName1 = file.getOriginalFilename();
						file.transferTo(new File(saveDir, fileName1));
						fileName = fileName + fileName1 + "/";
					}
				}
				board.setFilename(fileName);
			}
			reviewsService.writePost(board);
			mv = new ModelAndView("redirect:getPost.do?no=" + board.getNo());
		} catch (Exception e) {
			e.printStackTrace();
			mv.setViewName("tiles/error/error.jsp");
		}
		return mv;
	}

	// 글 목록 조회 처리하는 handler 메소드
	@RequestMapping("list.do")
	public String list(@RequestParam(defaultValue = "1") String page,
			ModelMap model) throws Exception {

		String url = null;
		int paging = 1;
		try {
			paging = Integer.parseInt(page);
			url = "tiles/reviewsboard/list.jsp";
		} catch (Exception e) {
			url = "tiles/error/error.jsp";
		}
		Map map = reviewsService.getReviewsBoardList(paging);
		model.addAllAttributes(map);
		return url;
	}

	// 한 개의 게시물을 조회하는 handler 메소드
	@RequestMapping("getPost.do")
	public String getPost(int no, ModelMap map){
		String url = null;
		
		try {
			List<Comment> comment = reviewsService.getCommentByNo(no);
			ReviewsBoard board = reviewsService.getPostByNo(no);
			if(comment != null){
				board.setComment(comment);
			}
			if(board.getFilename() != null){
					map.addAttribute("filename", board.getFilename());
			}
			map.addAttribute("reviewsboard", board);
			url = "tiles/reviewsboard/show_post.jsp";
		}catch(Exception e){
			e.printStackTrace();
			map.addAttribute("error_message", "글 조회 중 오류 발생 :" + e.getMessage());
			url = "tiles/error/error.jsp";
		}
		return url;
	}

	// 수정폼으로의 이동을 처리하는 handler 메소드
	@RequestMapping("updateForm.do")
	public String updateForm(int no, ModelMap map) {
		String url = null;

		try {
			ReviewsBoard board = reviewsService.getPostByNoForForm(no);
			if (board.getFilename() != null) {
				String[] str = board.getFilename().split("/");
				for (String file : str) {
					int i = 0;
					i++;
					map.addAttribute("filename" + i, file);
				}
			}
			map.addAttribute("reviewsboard", board);
			url = "tiles/reviewsboard/update_form.jsp";
		} catch (Exception e) {
			e.printStackTrace();
			map.addAttribute("error_message",
					"수정 게시물 조회 중 오류 발생 : " + e.getMessage());
			url = "tiles/error/error.jsp";
		}

		return url;
	}

	// 클라이언트가 수정한 글을 처리하는 handler 메소드
	@RequestMapping("updatePost.do")
	public ModelAndView updatePost(ReviewsBoard board, int page) {
		ModelAndView mv = null;

		try {
			reviewsService.updatePost(board);
			mv = new ModelAndView("redirect:getPost.do?no=" + board.getNo()
					+ "&page=" + page);
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("tiles/error/error.jsp",
					"error_message", "수정처리 도중 오류 발생 : " + e.getMessage());
		}

		return mv;
	}

	// 게시글 하나를 삭제처리하는 메소드
	@RequestMapping("deletePost.do")
	public String deletePost(int no, int page, ModelMap map) {
		String url = null;

		try {
			reviewsService.deletePost(no);
			reviewsService.deleteCommentByNo(no);
			url = "redirect:list.do?page=" + page;
		} catch (Exception e) {
			e.printStackTrace();
			url = "tiles/error/error.jsp";
			map.addAttribute("error_message", "삭제 도중 오류 발생 : " + e.getMessage());
		}

		return url;
	}

	//댓글을 DB에 insert 및 페이지에 출력
	@RequestMapping("write_comment.do")
	public String writeComment(Comment comment,  ModelMap map){
		String url = null;
		
		try {
			reviewsService.writeComment(comment);
			comment = reviewsService.getComment(comment.getCmNo());
			ReviewsBoard board = reviewsService.getPostByNoForForm(comment.getNo());
			map.addAttribute("comment", comment);
			url = "jsonView";
		} catch(Exception e){
			e.printStackTrace();
			url = "tiles/error/error.jsp";
		}
		return url;
	}
	
	//댓글 수정
	@RequestMapping("update_comment.do")
	public String updateComment(Comment comment, ModelMap map){
		String url = null;
		
		try {
			reviewsService.updateComment(comment);
			comment = reviewsService.getComment(comment.getCmNo());
			map.put("comment", comment);
			url = "jsonView";
		} catch(Exception e){
			url = "tiles/error/error.jsp";
			map.addAttribute("error_message", "댓글 수정 중 오류 발생 : "+e.getMessage());
		}
		
		return url;
	}
	
	//댓글 하나 삭제
	@RequestMapping("delete_comment.do")
	public String deleteComment(int cmNo){
		String url = null;
		
		try {
			reviewsService.deleteComment(cmNo);
			url = "jsonView";
		} catch(Exception e){
			url = "tiles/error/error.jsp";
		}
		return url;
	}
	
	//검색 
	@RequestMapping("search_list.do")
	public String SearChList(String searchBy, String query, @RequestParam(defaultValue="1") String page, ModelMap model){
		String url = null;
		int paging = 1;
		int search = 0;
		Map map = new HashMap();
		
		try {
			search = Integer.parseInt(searchBy);
			paging = Integer.parseInt(page);
			map = reviewsService.getSearchList(paging, search, query);
			url = "tiles/reviewsboard/search_list.jsp?page="+paging;
		} catch(Exception e){
			url = "tiles/error/error.jsp";
		}
		model.addAllAttributes(map);
		
		return url;
	}
	
}
























